package org.willthink.common;

import org.apache.log4j.Logger;

public class NoticePageUtil {
	
	private static Logger logger = Logger.getLogger(NoticePageUtil.class);
	
	private int curPageNo;
	private int totalCnt;
	
	private int firstPageNo;
	private int lastPageNo;
	
	private boolean hasNext;
	private boolean hasPrevious;
	
	public NoticePageUtil(int curPageNo, int totalCnt) {
		this.curPageNo = curPageNo;
		this.totalCnt = totalCnt;
		
		calcFirstPageNo();
		calcLastPageNo();
	}
	
	//첫번째 페이지 번호를 계산한다.
	private void calcFirstPageNo(){
		firstPageNo = (int) ((Math.ceil(curPageNo/10.0)*10)) - 9;
		if(firstPageNo !=1 ){
			hasPrevious = true;
		}
		
		lastPageNo = firstPageNo + (10-1);
	}
	
	//마지막 페이지 번호를 계산한다.
	private void calcLastPageNo(){
		int temp = (int)Math.ceil(totalCnt/ 10.0);
		
		if(temp < lastPageNo){
			lastPageNo = temp;
		}else if(temp > lastPageNo){
			hasNext = true;
		}
	}
	
	public String getPageStr(String linkStr){
		String template = "<a href=" + linkStr + ">:v2</a>";
		
		StringBuffer buffer =  new StringBuffer();
		
		if(hasPrevious){
			buffer.append(template.replaceAll(":v2", " < ").replaceAll(":v1", "" + (firstPageNo-1)));
		}
		
		for(int i=firstPageNo; i<=lastPageNo; i++){
			buffer.append(template.replaceAll(":v2", ""+i).replaceAll(":v1", ""+i));
		}
		
		if(hasNext){
			buffer.append(template.replaceAll(":v2"," > ").replaceAll(":v1", "" + (lastPageNo +1)));
		}
		
		return buffer.toString();
	}
	
	public static void main(String[] args) {
		NoticePageUtil pageUtil = new NoticePageUtil(12, 201);
		System.out.println(pageUtil.getPageStr("/notice/noticeList.think?pageNo=:v1"));
	}
}
